package com.qingke.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.qingke.pojo.Product;

public class ProductManagementDAO {
	protected static SessionFactory sf=null;
	protected static Session session=null;
	
	static {
		sf = new Configuration().configure().buildSessionFactory();
		session = sf.openSession();
	}
    
	public <T> List<T> get(Class<T> classType,Map<String,Object> map){
		DetachedCriteria detachCriteria=DetachedCriteria.forClass(classType);
		Criteria criteria=detachCriteria.getExecutableCriteria(session);
		if(map!=null)
			criteria.add(Restrictions.allEq(map));
		@SuppressWarnings("unchecked")
		List<T> list=criteria.list(); 
		return list;
	}
	
	public Product selectById(Integer id){
		return session.get(Product.class, id);
	}
	
	public boolean insertProduct(Product product){
		session.clear();
		Transaction tx=session.beginTransaction();
		try{
			session.save(product);
			tx.commit();
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
	}
	
	public boolean deleteProduct(Product product){
		Transaction tx=session.beginTransaction();
		try{
			session.delete(product);
			tx.commit();
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
	}
	
	public boolean updateProduct(Product product){
		Transaction tx=session.beginTransaction();
		try{
			session.saveOrUpdate(product);
			tx.commit();
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
			return false;
		}
		return true;
	}
	
	public List<Product> selectProduct(Integer id,String name,String description,Double pricelow,Double pricehigh,Integer quantitylow,Integer quantityhigh){
		DetachedCriteria detachCriteria=DetachedCriteria.forClass(Product.class);
		Criteria criteria=detachCriteria.getExecutableCriteria(session);
		if(id!=null)
			criteria.add(Restrictions.eq("id", id));
		if(name!=null)
			criteria.add(Restrictions.like("name", "%"+name+"%"));
		if(description!=null)
			criteria.add(Restrictions.like("description", "%"+description+"%"));
		if(pricelow!=null)
			criteria.add(Restrictions.ge("price", pricelow));
		if(pricehigh!=null)
			criteria.add(Restrictions.le("price", pricehigh));
		if(quantitylow!=null)
			criteria.add(Restrictions.ge("quantity", quantitylow));
		if(quantityhigh!=null)
			criteria.add(Restrictions.le("quantity", quantityhigh));
		@SuppressWarnings("unchecked")
		List<Product> list=criteria.list(); 
		return list;
	}
	
	
}
